package com.zmx.doctor.view.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.zmx.doctor.BaseActivity;
import com.zmx.doctor.R;
import com.zmx.doctor.adapter.GoodsOrderDetailsAdapter;
import com.zmx.doctor.listener.InformUpdateListenerManager;
import com.zmx.doctor.okhttp.OkHttp3ClientManager;
import com.zmx.doctor.pojo.GoodsOrder;
import com.zmx.doctor.utils.AllUtil;
import com.zmx.doctor.view.util.MySharedPreferences;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class GoodOrderDetailsActivity extends BaseActivity {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.title)
    EditText title;
    @BindView(R.id.yizu)
    EditText yizu;
    @BindView(R.id.submit)
    Button submit;

    private GoodsOrderDetailsAdapter adapter;
    private List<GoodsOrder> goods_car;

    private Integer logo;
    private String ask_id, p_id,z_type,temp_id;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_good_order_details;
    }

    @Override
    protected void initViews() {

        ButterKnife.bind(this);
        setToolbar(R.id.tool_bar);

        logo = Integer.parseInt(getIntent().getStringExtra("logo"));
        z_type = this.getIntent().getStringExtra("z_type");
        temp_id = this.getIntent().getStringExtra("temp_id");

        goods_car = (List<GoodsOrder>) this.getIntent().getSerializableExtra("lists");
        recyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        adapter = new GoodsOrderDetailsAdapter(mActivity,handler,1);
        recyclerView.setAdapter(adapter);
        adapter.setListAndNotifyDataSetChanged(goods_car);

        if (logo == 1) {

            submit.setText("发 送 处 方");
            ask_id = getIntent().getStringExtra("ask_id");
            p_id = getIntent().getStringExtra("p_id");


        } else {

            submit.setText("保 存 处 方");

        }

    }


    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case 1:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        Toast(object.getString("msg"));
                        if (object.getInt("code") == 1) {
                            finish();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

                case 2:


                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        Toast(object.getString("msg"));
                        if (object.getInt("code") == 1) {

                            JSONObject data = object.getJSONObject("data");

                            InformUpdateListenerManager informUpdateListenerManager = new InformUpdateListenerManager(mActivity);
                            informUpdateListenerManager.getInstance(mActivity).updateChat(data.getString("content"));
                            finish();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                    break;

                case 3:
                    showPhoto(goods_car.get(msg.arg1),msg.arg1);
                    break;

                case 4:


                    new AlertDialog.Builder(mActivity)
                            .setTitle("提示")
                            .setMessage("确定删除该药品？")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {

                                    goods_car.remove(goods_car.get(msg.arg1));
                                    adapter.notifyItemRemoved(msg.arg1);
                                    adapter.notifyItemRangeRemoved(msg.arg1, goods_car.size());

                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {

                                }
                            }).show();

                    break;

            }

        }
    };

    private Dialog modify_dialogs;//弹出框
    public void showPhoto(GoodsOrder go,Integer listPosition) {

        View view;//选择性别的view

        modify_dialogs = new Dialog(mActivity, R.style.ActionSheetDialogStyle);
        //填充对话框的布局
        view = LayoutInflater.from(mActivity).inflate(R.layout.dialog_shopping, null);
        //将布局设置给Dialog
        modify_dialogs.setContentView(view);
        //获取当前Activity所在的窗体
        Window dialogWindow = modify_dialogs.getWindow();

        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        //        lp.y = 20;//设置Dialog距离底部的距离

        //// 以下这两句是为了保证按钮可以水平满屏
        lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
        lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        // 设置显示位置
        modify_dialogs.onWindowAttributesChanged(lp);
        //       将属性设置给窗体
//        modify_dialogs.setCanceledOnTouchOutside(false);
        modify_dialogs.show();//显示对话框

        TextView name = view.findViewById(R.id.name);
        name.setText("商品名称" + go.getGoods_name());
        TextView desc = view.findViewById(R.id.desc);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

            if (go.getDescribe() != null){

                desc.setText("药品描述：" + Html.fromHtml((go.getDescribe()), 10));

            }else {
                desc.setVisibility(View.GONE);
            }

        }
        EditText y_number = view.findViewById(R.id.y_number);
        y_number.setText(go.getNumber()+"");
        EditText y_sm = view.findViewById(R.id.y_sm);
        y_sm.setText(go.getDescribes());
        EditText e_day = view.findViewById(R.id.e_day);
        e_day.setText(go.getDay());

        TextView regular = view.findViewById(R.id.regular);
        regular.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                final String[] items = {"片/次", "瓶/次", "剂/次"};
                showNotice(regular,items);
            }
        });
        TextView e_rate = view.findViewById(R.id.e_rate);
        e_rate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                final String[] items = {"每日一次", "每日二次", "每日三次"};
                showNotice(e_rate,items);
            }
        });
        TextView e_usage = view.findViewById(R.id.e_usage);
        e_usage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                final String[] items = {"口服", "外用", "注射"};
                showNotice(e_usage,items);
            }
        });

        Button submit = view.findViewById(R.id.submit);
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (y_number.getText().toString().equals("")){

                    Toast("数量不能为空！");
                    return;

                }

                if (y_sm.getText().toString().equals("")){

                    Toast("使用说明不能为空！");
                    return;

                }
                if (e_day.getText().toString().equals("")){

                    Toast("用药时长不能为空！");
                    return;

                }

                go.setNumber(Integer.parseInt(y_number.getText().toString()));
                go.setUsage(y_sm.getText().toString());
                go.setDay(e_day.getText().toString());
                go.setType(1);
                goods_car.set(listPosition,go);
                adapter.notifyDataSetChanged();
                modify_dialogs.dismiss();

            }
        });

    }

    private AlertDialog alertDialog1; //信息框
    public void showNotice(TextView textView,String[] items) {
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(mActivity);
        alertBuilder.setTitle("请选择");
        alertBuilder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                textView.setText(items[i]);
                alertDialog1.dismiss();
            }
        });
        alertDialog1 = alertBuilder.create();
        alertDialog1.show();
    }



    @OnClick(R.id.submit)
    public void onViewClicked() {

        if (title.getText().toString().equals("")) {

            Toast("输入处方标题");
            return;

        }

        if (goods_car.size()<=0){
            Toast("没有药品，无法提交");
            return;

        }

        if (logo == 1) {

            if (Integer.parseInt(z_type) == 1){

                sendMake();

            }else {

                sendMakes();

            }


        } else {
            setMakeTemp();
        }


    }

    public void setMakeTemp() {

        Gson gson = new Gson();
        String taskInfo = gson.toJson(goods_car);

        List<String> l = new ArrayList<>();
        l.add(yizu.getText().toString());
        l.add(taskInfo + "");
        l.add(title.getText().toString());

        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(l)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "setMakeTemp");
        params.put("data[make]", taskInfo);
        params.put("data[advice]", yizu.getText().toString());
        params.put("data[title]", title.getText().toString());
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/admin/api.make/entry", params, handler, 1, 404);

    }

    public void sendMake() {

        Gson gson = new Gson();
        String taskInfo = gson.toJson(goods_car);

        List<String> l = new ArrayList<>();
        l.add(yizu.getText().toString());
        l.add(ask_id);
        l.add(taskInfo + "");
        l.add(p_id);
        l.add(title.getText().toString());

        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(l)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "sendMake");
        params.put("data[make]", taskInfo);
        params.put("data[ask_id]", ask_id);
        params.put("data[patient_id]", p_id);
        params.put("data[advice]", yizu.getText().toString());
        params.put("data[title]", title.getText().toString());
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/admin/api.make/entry", params, handler, 2, 404);

    }

    public void sendMakes() {

        Gson gson = new Gson();
        String taskInfo = gson.toJson(goods_car);

        List<String> l = new ArrayList<>();
        l.add(yizu.getText().toString());
        l.add(ask_id);
        l.add(taskInfo + "");
        l.add(p_id);
        l.add(temp_id);
        l.add(title.getText().toString());

        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(l)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "teamSendMake");
        params.put("data[make]", taskInfo);
        params.put("data[ask_id]", ask_id);
        params.put("data[patient_id]", p_id);
        params.put("data[advice]", yizu.getText().toString());
        params.put("data[team_id]", temp_id);
        params.put("data[title]", title.getText().toString());
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/admin/api.team/entry", params, handler, 2, 404);

    }


}
